package com.sesame.util;

import sun.misc.Launcher;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * FileJarUtil
 *
 * @author 01249527-王江海
 * @date 2017-09-19 16:52
 * @classpath com.sesame.util.FileJarUtil
 * @Description:
 */
public class FileJarUtil {

    public static List<String> getDir(String pathName) {
        List<String> list = new ArrayList<>();

        try {
//        String classPath = FileJarUtil.class.getProtectionDomain().getCodeSource().getLocation().getPath();
            URL classUrl = FileJarUtil.class.getResource("FileJarUtil.class");
            String classPath = classUrl.toString();
            String jarPath = classPath.substring("jar:file:/".length(), classPath.indexOf("!/BOOT-INF"));

            System.out.println("classPath=" + classPath);
            System.out.println("jarPath=" + jarPath);

            if (classPath.startsWith("jar:")) {
                System.out.println("jar 运行的");

                File jarFile = new File(jarPath);
                JarFile jar = new JarFile(jarFile);

                Enumeration<JarEntry> entries = jar.entries(); //将所有条目放入JAR中
                while (entries.hasMoreElements()) {
                    String name = entries.nextElement().getName();
                    if (name.contains(pathName)) { //根据路径进行筛选
                        System.out.println(name);
                    }
                }
                jar.close();

            } else {
                System.out.println("war 或 IDE 运行的");


                final URL url = Launcher.class.getResource("/" + pathName);
                if (url != null) {
                    try {
                        final File apps = new File(url.toURI());
                        for (File app : apps.listFiles()) {
                            System.out.println(app);
                        }
                    } catch (Exception ex) {
                        // never happens
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }
}